const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const app = express();

// 跨域配置
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*'); // 允许所有域
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
});

// 自定义存储路径
const storageDir = './static'; // 视频文件存储位置
if (!fs.existsSync(storageDir)) {
  fs.mkdirSync(storageDir, { recursive: true });
}

// 存储配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, storageDir);
  },
  filename: function (req, file, cb) {
    // 保留原始文件名并处理冲突
    const originalname = file.originalname;
    const ext = path.extname(originalname);
    const basename = path.basename(originalname, ext);
    
    let finalName = originalname;
    let counter = 1;
    
    while (fs.existsSync(path.join(storageDir, finalName))) {
      finalName = `${basename}-${counter}${ext}`;
      counter++;
    }
    
    cb(null, finalName);
  }
});

// 文件过滤
const fileFilter = (req, file, cb) => {
  const allowedTypes = [
    'video/mp4'
  ];
  
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('不允许的文件类型'), false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 10 // 10MB
  },
  fileFilter: fileFilter
}).single('file');

// 上传路由 - 部署在/upload路径
app.post('/upload', (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      if (err.code === 'LIMIT_FILE_SIZE') {
        return res.status(413).json({ 
          code: 413,
          message: '文件大小超过10MB限制'
        });
      }
      return res.status(415).json({
        code: 415,
        message: err.message || '文件上传失败'
      });
    }
    
    if (!req.file) {
      return res.status(400).json({
        code: 400,
        message: '未选择文件'
      });
    }
    
    res.status(200).json({
      code: 200,
      data: {
        originalName: req.file.originalname,
        fileName: req.file.filename,
        size: req.file.size,
        url: `/static/${req.file.filename}`, // 访问路径
        mimetype: req.file.mimetype
      }
    });
  });
});

// 静态文件访问 - 配置/dmcy/static为静态资源目录
app.use('/static', express.static(storageDir));

// 错误处理
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    code: 500,
    message: '服务器内部错误'
  });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
  console.log(`服务已启动，监听端口 ${PORT}`);
  console.log(`上传目录: ${storageDir}`);
  console.log(`访问路径: http://localhost:${PORT}/upload`);
});

module.exports = server;